package com.wugui.datax.rpc.remoting.net.impl.netty.codec;

import com.wugui.datax.rpc.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * decoder
 *
 * @author xuxueli 2015-10-29 19:02:36
 */
public class NettyDecoder extends ByteToMessageDecoder {

  private final Class<?> genericClass;

  private final Serializer serializer;

  public NettyDecoder(Class<?> genericClass, final Serializer serializer) {
    this.genericClass = genericClass;
    this.serializer = serializer;
  }

  @Override
  public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < 4) {
      return;
    }
    in.markReaderIndex();
    int dataLength = in.readInt();
    if (dataLength < 0) {
      ctx.close();
    }
    if (in.readableBytes() < dataLength) {
      in.resetReaderIndex();
      return; // fix 1024k buffer splice limix
    }
    byte[] data = new byte[dataLength];
    in.readBytes(data);

    Object obj = serializer.deserialize(data, genericClass);
    out.add(obj);
  }
}
